#include "protocol.h"

namespace CustomProtocol {

    QByteArray packData(const QByteArray& content) {
        QByteArray packet;
        QDataStream stream(&packet, QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_5_13);

        // 写入起始标记
        stream << START_MARKER;

        // 写入数据长度
        quint32 length = static_cast<quint32>(content.size());
        stream << length;

        // 写入内容数据
        stream.writeRawData(content.constData(), content.size());

        // 写入结束标记
        stream << END_MARKER;

        // 防粘包 写入长度前缀
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_5_13);
        out << (quint32)packet.size();
        out.writeRawData(packet.constData(), packet.size());

        return block;
    }

    QByteArray unpackData(const QByteArray& packet, bool& success) {
        success = false;
        QByteArray content;

        if (packet.size() < 16) { // 最小长度检查(4+4+4+0+4)
            return content;
        }

        QDataStream stream(packet);
        stream.setVersion(QDataStream::Qt_5_13);

        quint32 blockSize = 0;
        stream >> blockSize;
        // 协议包长度是否合理
        if (blockSize != packet.size() - 4) {
            return content;
        }

        quint32 startMarker;
        stream >> startMarker;
        if (startMarker != START_MARKER) {
            return content;
        }

        quint32 length;
        stream >> length;
        // 检查数据长度是否合理
        if (length > static_cast<quint32>(packet.size())) {
            return content;
        }

        // 读取内容数据
        content.resize(length);
        if (stream.readRawData(content.data(), length) != length) {
            content.clear();
            return content;
        }

        quint32 endMarker;
        stream >> endMarker;

        if (endMarker != END_MARKER) {
            content.clear();
            return content;
        }

        success = true;
        return content;
    }

} // namespace CustomProtocol
